﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using SIS_Wcf_Server;
using SIS_Wcf_Server.Model;

namespace SIS_Wcf_Server.Search
{
    /// <summary>
    /// Adds a approximated GPS posistion in case there is no 
    /// GPS senser result in the request.
    /// </summary>
    public class GpsExtenderDecorator : ISearch
    {
        ISearch _inner;
        IData   _data;

        public GpsExtenderDecorator(IData data, ISearch inner)
        {
            _inner = inner;
            _data = data;
        }



        #region ISearch Members

        public List<Model.RestInformation> DoSearch(List<Model.Lokation> locations)
        {
            
            bool bGotGps = false;

            foreach (Lokation l in locations)
            {
                if (l.isGps())
                {
                    bGotGps = true;
                    break;
                }
            }

            if ( ! bGotGps )
            {
                int foundGeoCodedNets = 0;
                
                double? lat = 0.0;
                double? lng = 0.0;

                // Find netId for alle de nets der er her, og tag dem som "ikke geocodede"
                foreach ( Lokation l in locations )
                {
                    net n = _data.getNetFromLokation(l);
                    
                    if (n != null)
                    {
                        if (n.geocoded_nets.Count > 0)
                        {
                            lat = n.geocoded_nets.First().Lat;
                            lng = n.geocoded_nets.First().Long;
                            foundGeoCodedNets++;
                        }
                    }
                }

                if (foundGeoCodedNets > 0)
                {
                    lat /= foundGeoCodedNets;
                    lng /= foundGeoCodedNets;

                    locations.Add( new Lokation() { Type = "GPS", Value = lat.ToString().Replace(",", ",") + "/" + lng.ToString().Replace(",", ",") } );

                }
            }
            List<Model.RestInformation> result = _inner.DoSearch(locations);
            return result;
        }
             
        public List<Model.RestInformation> DoListAll()
        {
            return _inner.DoListAll();
        }

        #endregion
    }
}